package com.authine.cloudpivot.ext.controller;


import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.*;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.type.QueryDisplayType;
import com.authine.cloudpivot.web.api.controller.runtime.FormRuntimeController;
import com.authine.cloudpivot.web.api.util.HttpUtilNew;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import redis.clients.jedis.Jedis;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/fz")
@Slf4j
public class FZController extends FormRuntimeController {


    @Value("${fzv.addressBook.corpsecret}")
    private String corpsecret;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;

    /**
     * 获取供应商编码
     *
     * @param
     * @return
     */
    @GetMapping("/getSupplierNo")
    public ResponseResult getSupplierNo() {
        String supplierNo = "";
        //获取流程的数据
        BizObjectFacade bizObjectFacade = this.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("supplierNo", "eac05f174820423890b78c10602ceff4");
        if (null != bizObject) {
            String str = bizObject.getString("supplierNo");
            String[] ss = str.split("\\.");
            if (ss.length > 0) {
                supplierNo = ss[0];
                Integer next = Integer.valueOf(supplierNo) + 1;
                bizObject.getData().put("supplierNo", next);
                bizObjectFacade.saveBizObject(bizObject.getOwner().getId(), bizObject, true);
                return super.getOkResponseResult(supplierNo, "成功");
            }

        }

        return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "系统没有初始的供应商编号");
    }

    /**
     * 供应商更新报价
     *
     * @param objId
     * @param wId"
     * @return
     */
    @ApiOperation("供应商更新报价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objId", value = "业务对象id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "wId", value = "业务流程id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/updatePrice")
    public ResponseResult getDealerListReport(String objId, String wId) {
        log.info("供应商更新报价-----start");
        log.info("获取参数:objId={}，wId={}", objId, wId);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(wId)) {
            log.info("参数不完整，直接结束");
            return getErrResponseResult(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), "参数不完整，直接结束！");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("supplier_quotation", objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "业务对象不存在！");
        }
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(bizObject.getWorkflowInstanceId());
        if (wiModel == null) {
            log.info("业务流程对象不存在");
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "业务流程对象不存在！");
        }
        //获取父流程数据
        WorkflowInstanceModel parentWiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wiModel.getParentId());
        if (parentWiModel == null) {
            log.info("主流程对象不存在");
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "主流程对象不存在！");
        }
        BizObjectCreatedModel parentBizObjectModel = bizObjectFacade.getBizObject("quotation", parentWiModel.getBizObjectId());
        if (parentBizObjectModel == null) {
            log.info("主流程业务对象不存在");
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "主流程业务对象不存在！");
        }
        String userId = bizObject.getCreater().getId();
        //获取供应商列表
        List<SelectionValue> originatorList = (List<SelectionValue>) parentBizObjectModel.get("supplier");

        if (!CollectionUtils.isEmpty(originatorList)) {
            for(int i =0;i < originatorList.size();i++ ){
                String supplierId = String.valueOf(originatorList.get(i).getId());
                log.info("子流程供应商id={},父流程供应商id={}",userId,supplierId);
                //匹配子流程的供应商
                if(userId.equals(supplierId)){
                    Map<String, Object> map = new HashMap<>();
                    //供应商报价预处理
                    List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("supplier_quotation_detail");
                    for(Map<String, Object> m :list){
                        map.put(String.valueOf(m.get("PMK01"))+String.valueOf(m.get("PML02")),m);
                    }
                    log.info("子流程供应商报价={}",map);
                    //插入报价
                    List<Map<String, Object>> list2 = (List<Map<String, Object>>) parentBizObjectModel.get("quotation_detail");
                    for(Map<String, Object> m :list2){
                        String primaryKey = String.valueOf(m.get("PMK01")) + String.valueOf(m.get("PML02"));
                        if(null != map.get(primaryKey)){
                            Map data = (Map) map.get(primaryKey);
                            m.put("rowStatus","Modified");
                            m.put("PMJ07_"+(i+1),data.get("PMJ07"));
                            m.put("PMJ07T_"+(i+1),data.get("PMJ07T"));
                            log.info("父流程供应商报价={}",m);
                        }

                    }
                    parentBizObjectModel.getData().put("quotation_detail",list2);
                    log.info("父流程数据={}",parentBizObjectModel.getData());
                    bizObjectFacade.saveBizObject(parentBizObjectModel.getOwner().getId(), parentBizObjectModel, true);
                    break;
                }
            }

        }
        log.info("供应商更新报价-----end");
        return super.getOkResponseResult("供应商更新报价成功！");
    }
    @ApiOperation("获取送货单数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objId", value = "业务对象id", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/getDeliveryNoteNum")
    public ResponseResult getDeliveryNoteNum(String objId) {
        log.info("获取送货单数量-----start");
        log.info("获取参数:objId={}", objId);
        if (StringUtils.isBlank(objId)) {
            log.info("参数不完整，直接结束");
            return getErrResponseResult(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), "参数不完整，直接结束！");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("deliveryNote", objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "业务对象不存在！");
        }
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("deliveryNote_detail");
        for(Map<String, Object> map :list){
            map.put("notNumber",getDeliveryNoteNum(String.valueOf(map.get("PMM01")),String.valueOf(map.get("PMN02")),(BigDecimal) map.get("RVBS06")));
        }

        log.info("未发数量={}",list);
        log.info("获取送货单数量-----end");
        return super.getOkResponseResult(list,"获取送货单数量成功！");
    }

    @ApiOperation("验证是否发货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "PMM01", value = "采购单号", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/getIsDelivery")
    public ResponseResult getIsDelivery(String PMM01) {
        log.info("验证是否发货-----start");
        log.info("获取参数:PMM01={}", PMM01);
        if (StringUtils.isBlank(PMM01)) {
            log.info("参数不完整，直接结束");
            return getErrResponseResult(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), "参数不完整，直接结束！");
        }
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("deliveryNote");
        queryModel.setQueryCode("deliveryNote");
        /*List<FilterExpression> filterExpressionList = new ArrayList<FilterExpression>(){
            {
                add(Q.it("PMM01", FilterExpression.Op.Eq, PMM01));
            }
        };

        queryModel.setFilterExpr(Q.and(filterExpressionList));*/
        //queryModel.setFilterExpr(Q.it("PMM01", FilterExpression.Op.Eq, PMM01));
        BizObjectQueryModel.Options options = new BizObjectQueryModel.Options();
        options.setQueryDisplayType(QueryDisplayType.APPEND);
        options.setCustomDisplayColumns(Arrays.asList(new String[]{"deliveryNote_detail"}));
        queryModel.setOptions(options);
        List<BizObjectModel> list = (List<BizObjectModel>) getBizObjectFacade().queryBizObjects(queryModel).getContent();
        log.info("list={}",list);
        if (!CollectionUtils.isEmpty(list)) {
            for(BizObjectModel model :list){
                List<Map<String, Object>> data = (List<Map<String, Object>>) model.getData().get("deliveryNote_detail");
                log.info("data={}",data);
                if(!CollectionUtils.isEmpty(data)){
                    for(Map<String, Object> map :data){
                        log.info("PMM01={},date={}",PMM01,map.get("PMM01"));
                        if(PMM01.equals(map.get("PMM01"))){
                            log.info("进入判断>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            return super.getOkResponseResult(false,"已发货,不能进行撤回！");
                        }
                    }
                }

            }
        }



        log.info("验证是否发货----end");
        return super.getOkResponseResult(true,"未发货,可以进行撤回！");
        //return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(), "系统异常");
    }

    /**
     *
     * @param PMM01 采购单号
     * @param PMN02 采购项次
     * @param RVBS06 送货数量
     * @return
     */
    private BigDecimal getDeliveryNoteNum(String PMM01, String PMN02, BigDecimal RVBS06) {
        log.info("PMM01={},PMN02={},RVBS06={}",PMM01,PMN02,RVBS06);
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("cgdd_mx");
        queryModel.setQueryCode("cgdd_mx");
        List<FilterExpression> filterExpressionList = new ArrayList<FilterExpression>(){
            {
                add(Q.it("PMM01", FilterExpression.Op.Eq, PMM01));
                add(Q.it("PMN02", FilterExpression.Op.Eq, PMN02));
            }
        };

        queryModel.setFilterExpr(Q.and(filterExpressionList));
        Page<BizObjectModel> modelPage = getBizObjectFacade().queryBizObjects(queryModel);

        if (modelPage != null && !org.springframework.util.CollectionUtils.isEmpty(modelPage.getContent())) {
            List<? extends BizObjectModel> content = modelPage.getContent();
            if (!org.springframework.util.CollectionUtils.isEmpty(content)) {
                for (BizObjectModel model : content) {
                    BigDecimal reNum =(BigDecimal) model.getData().get("REMAINING");
                    if(null != reNum){
                        BigDecimal ret = reNum.add(RVBS06);
                        return ret;
                    }
                }
            }
        }
        return null;
    }
    @PostMapping("/addUser")
    public ResponseResult addUser(String supplierNo,String objectId) throws Exception {
        String token = getRedis();
        log.info("WxAddressBookToken={}",token);
        //获取流程的数据
        BizObjectFacade bizObjectFacade = this.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("changshangxinzeng", objectId);
        if(null != objectId){
            Map<String, Object> map = new HashMap<>();
            String[] array = new String[]{"133"};
            map.put("userid",supplierNo);
            map.put("name", (String) bizObject.get("PMC03"));
            //部门：供应商组织
            map.put("department",array);
            map.put("mobile",(String) bizObject.get("mobile"));
            log.info("创建人员接口入参={}",map);
            String res = HttpUtilNew.sendHttpPost(String.format("https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=%s&debug=1", token), JSONObject.toJSONString(map));
            log.info("创建人员接口出参={}",res);
            JSONObject jsonObject = JSONObject.parseObject(res);
            if("ok".equals(jsonObject.getString("errmsg"))){
                log.info("创建人员接口res={}",res);
                return getOkResponseResult("新增用户成功");
            }
            return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(),res);

        }

        return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(),"新增用户失败");
    }

    private  String  getRedis(){

        Jedis jedis = new Jedis(host);
        jedis.auth(password);
        log.info("连接redis成功");
        String WxAddressBookToken = jedis.get("WxAddressBookToken");
        if(StringUtils.isBlank(WxAddressBookToken)){
            String token = getToken();
            jedis.setex("WxAddressBookToken",7000, token);
            jedis.close();
            return  token;
        }
        return  WxAddressBookToken;
        //设置 redis 字符串数据

    }
    private String getToken (){
        String token = "";
        String res = HttpUtilNew.sendGet(String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", "wx981c62582a466954", corpsecret));
        log.info("获取的token={}",res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if("ok".equals(jsonObject.getString("errmsg"))){
            token = jsonObject.getString("access_token");
        }
        return token;
    }
}
